/**
 * 支付数据格式化工具
 * 负责将前端支付数据转换为后端需要的DTO结构
 */
export class PaymentDataFormatter {
  
  /**
   * 格式化支付数据为后端需要的结构
   * @param {Object} paymentData 前端支付数据
   * @returns {PatientRegistrationRequest} 格式化后的数据
   */
  static formatToBackend(paymentData) {
    const now = new Date();
    const currentTime = now.toISOString();

    console.log('格式化前的数据 - schedule_instance_id:', paymentData.appointmentInfo?.schedule_instance_id);
    
    return {
      patientVisitDTO: this.formatPatientVisitDTO(paymentData, currentTime),
      paymentMainDTO: this.formatPaymentMainDTO(paymentData, currentTime)
    };
  }
  
  /**
   * 格式化患者就诊记录DTO
   */
  static formatPatientVisitDTO(paymentData, currentTime) {
    const appointmentInfo = paymentData.appointmentInfo;
    const patientInfo = paymentData.patientInfo;
    
    return {
      appointment_id: paymentData.appointmentId,
      insurance_card_number: patientInfo.cardNumber || '',
      schedule_instance_id: appointmentInfo.schedule_instance_id || '',
      patient_name: patientInfo.name,
      id_number: patientInfo.idNumber || patientInfo.id,
      phone_number: patientInfo.phone || '',
      registration_time: currentTime,
      registration_fee: this.toDecimal(appointmentInfo.fee || 0.5),
      visit_type: 'outpatient',
      visit_status: 'registered',
      department_id: appointmentInfo.department_id,
      department_name: appointmentInfo.department,
      doctor_id: appointmentInfo.doctor_id,
      doctor_name: appointmentInfo.doctor,
      chief_complaint: '', // 就诊时填写
      medical_history: '', // 就诊时填写
      allergy_history: '', // 就诊时填写
      visit_time: null, // 就诊时更新
      complete_time: null, // 完成时更新
      create_time: currentTime,
      update_time: currentTime
    };
  }
  
  /**
   * 格式化收费主表DTO
   */
  static formatPaymentMainDTO(paymentData, currentTime) {
    const paymentInfo = paymentData.paymentInfo;
    const patientInfo = paymentData.patientInfo;
    const appointmentInfo = paymentData.appointmentInfo;
    const isInsurance = paymentInfo.mode === 'insurance';
    const isFullyCovered = paymentInfo.useInsurance && isInsurance;
    
    return {
      payment_no: this.generatePaymentNo(paymentData.appointmentId),
      visit_id: null, // 需要后端关联
      patient_name: patientInfo.name,
      id_number: patientInfo.idNumber || patientInfo.id,
      payment_type: 'registration',
      source_type: 'registration',
      source_id: null, // 需要后端关联
      department_id: appointmentInfo.department_id,
      department_name: appointmentInfo.department,
      payable_amount: this.toDecimal(paymentInfo.totalAmount),
      discount_amount: this.toDecimal(0),
      actual_amount: this.toDecimal(paymentInfo.payableAmount),
      paid_amount: this.toDecimal(paymentInfo.payableAmount),
      payment_method: this.getPaymentMethod(paymentInfo),
      insurance_card_number: patientInfo.insuranceCardNumber || '',
      insurance_payment: this.toDecimal(paymentInfo.insurancePayment),
      personal_payment: this.toDecimal(paymentInfo.selfPayment),
      payment_status: isFullyCovered ? 'completed' : 'pending',
      payment_time: isFullyCovered ? currentTime : null,
      operator_id: 0, // 自助机系统
      operator_name: '自助机系统',
      window_number: 'AUTO_001',
      notes: this.generatePaymentNotes(paymentData),
      create_time: currentTime,
      update_time: currentTime
    };
  }
  
  /**
   * 生成支付单号
   */
  static generatePaymentNo(appointmentId) {
    return `PAY${appointmentId.slice(2)}`;
  }
  
  /**
   * 确定支付方式
   */
  static getPaymentMethod(paymentInfo) {
    if (paymentInfo.mode === 'insurance') {
      return 'insurance';
    }
    // 自费支付时，可以根据实际情况返回具体支付方式
    return 'wechat'; // 默认微信支付，实际中应该由用户选择
  }
  
  /**
   * 生成支付备注
   */
  static generatePaymentNotes(paymentData) {
    const notes = [];
    const paymentInfo = paymentData.paymentInfo;
    
    if (paymentInfo.useInsurance) {
      notes.push('生育保险已启用');
    }
    
    if (paymentInfo.mode === 'insurance') {
      notes.push(`医保支付: ¥${paymentInfo.insurancePayment.toFixed(2)}`);
      if (paymentInfo.insuranceBalance > 0) {
        notes.push(`医保余额: ¥${paymentInfo.insuranceBalance.toFixed(2)}`);
      }
    }
    
    if (paymentInfo.selfPayment > 0) {
      notes.push(`个人支付: ¥${paymentInfo.selfPayment.toFixed(2)}`);
    } else {
      notes.push('个人支付: 0元');
    }
    
    return notes.join('; ');
  }
  
  /**
   * 转换为小数（模拟BigDecimal）
   */
  static toDecimal(value) {
    return Number.parseFloat(Number(value).toFixed(2));
  }
  
  /**
   * 验证支付数据完整性
   */
  static validatePaymentData(paymentData) {
    const requiredFields = [
      'appointmentId',
      'patientInfo.name',
      'appointmentInfo.department_id',
      'paymentInfo.totalAmount'
    ];
    
    for (const field of requiredFields) {
      const value = this.getNestedValue(paymentData, field);
      if (value === undefined || value === null || value === '') {
        throw new Error(`支付数据缺少必要字段: ${field}`);
      }
    }
    
    return true;
  }
  
  /**
   * 获取嵌套对象值
   */
  static getNestedValue(obj, path) {
    return path.split('.').reduce((current, key) => {
      return current && current[key] !== undefined ? current[key] : undefined;
    }, obj);
  }
}